package com.jyu.filter;

import com.jyu.domain.LoginUser;
import com.jyu.util.JwtUtil;
import com.jyu.util.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class JWTFilter extends OncePerRequestFilter {

    @Resource
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //拦截所有请求，并获取请求头中携带的token
        String token = httpServletRequest.getHeader("token");
        //如果没有携带请求头，直接放行
        //当请求过了自定义JWTFilter，SpringSecurity 框架中会对除了无需拦截的请求（不需要用户登陆的接口，例如登录接口无需拦截）以外的所有接口提供保护
        //在后续过滤器链中，都会需要去SecurityContextHolder去拿已认证的authentication，如果没有获取到，SpringSecurity框架会直接拦截
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        //解析token
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            //直接抛出异常会被SpringSecurity中的异常过滤器捕获
            throw new RuntimeException("传入的token非法");
        }
        //根据解析到的id查询redis
        String redisKey = "login:" + userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(loginUser)) {
            throw new RuntimeException("用户未登录");
        }
        //用户登录，刷新redis用户的过期时间
        redisCache.expire(redisKey,60, TimeUnit.SECONDS);
        //将查询到的用户信息存入SecurityContextHolder，这一步也是模拟UsernamePasswordAuthenticationFilterSpring Security过滤器认证的最后一步
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
